package com.example

import com.example.plugins.UserSession
import com.example.plugins.routes.distributorRouting
import com.example.plugins.routes.ordersRouting
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
import io.ktor.util.*
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction

fun main() {
    val database = Database.connect(
        "jdbc:postgresql://localhost:2000/ktor",
        driver = "org.postgresql.Driver", user = "admin", password = "admin"
    )

    embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
        .start(wait = true)

    transaction(database) {
        SchemaUtils.create(Distributors)
    }
}

fun Application.module() {
    routing {
        distributorRouting()
        ordersRouting()
    }

    install(ContentNegotiation) {
        json()
    }

    install(Sessions) {
        val secretEncryptKey = hex("00112233445566778899aabbccddeeff")
        val secretSignKey = hex("6819b57a326945c1968f45236589")

        cookie<UserSession>("user_session") {
            cookie.path = "/"
            cookie.maxAgeInSeconds = 30
            transform(SessionTransportTransformerEncrypt(secretEncryptKey, secretSignKey))
        }
    }
}
